#!/usr/bin/python

# scheduler.py: run updates when needed

# Copyright 2011 Portland Transport

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Authors:
# Matt Conway: main code

import csv, feedparser, pickle, subprocess, os

AGENCY_FOLDER=os.environ['HOME'] + '/agencies'

database = csv.reader(open('agencies.csv'))

# if it doesn't exist, it'll need to be created manually
datesFile = open('dates.pcl', 'r')
dates = pickle.load(datesFile)
datesFile.close()

toUpdate = []
updateDates = {}

for line in database:
    fp = feedparser.parse(line[1])

    try:
        lastFile = fp.feed.updated_parsed
    except AttributeError:
        print 'Could not retrieve feed for %s' % line[0]
        continue
    
    # Save this, if the update is successful it will be written out
    updateDates[line[0]] = lastFile
    
    try:
        lastUpdate = dates[line[0]]
    except KeyError:
        print 'Marking agency %s for update' % line[0]
        toUpdate.append(line[0])
        continue
    else:
        if lastFile > lastUpdate:
            print 'Marking agency %s for update' % line[0]
            toUpdate.append(line[0])
            continue

    print 'Agency %s is up to date' % line[0]

print 'Updating agencies:'
for i in toUpdate:
    print ' * %s' % i

for agency in toUpdate:
    # This is not subject to shell injection, but if there are 
    # bad commands in the agencies file, that could be a problem.
    if subprocess.call(['/bin/sh', AGENCY_FOLDER + '/' + agency]) == 0:
        print 'Agency %s updated successfully' % agency
        dates[agency] = updateDates[agency]
    else:
        print 'Error updating agency %s' % agency

pickle.dump(dates, open('dates.pcl', 'w'))
